package com.witmore.neutron.ai.web.apiv2.login;

import com.jk.common.response.ResponseResult;
import com.witmore.neutron.ai.db.entity.UserDO;
import com.witmore.neutron.ai.db.mapper.UserMapper;
import com.witmore.neutron.ai.web.annotation.NoLoginRequired;
import com.witmore.neutron.ai.web.filter.GlobalAccountSession;
import com.witmore.neutron.ai.web.wechat.dto.CreateQrCodeParam;
import com.witmore.neutron.ai.web.wechat.dto.CreateQrCodeResponse;
import com.witmore.neutron.ai.web.wechat.dto.QrCodeResult;
import com.witmore.neutron.ai.web.wechat.service.WechatService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;

/**
 * V2 微信扫码登录控制器
 * Author: 豆子高
 * Date: 2025/9/4 14:10
 */
@Slf4j
@RestController
@RequestMapping("/v2/wechat/scan")
public class WechatScanControllerV2 {
    @Autowired
    private WechatService wechatService;

    @Autowired
    private UserMapper userMapper;

    private final static String FR_STOCK = "ai";

    /**
     * 生成带参数的二维码
     */
    @NoLoginRequired
    @PostMapping("/createQrcode")
    public ResponseResult<QrCodeResult> createQrCode(@RequestBody CreateQrCodeParam param) {
        String sceneStr = param.getSceneValue();
        log.info("生成二维码参数：{}", param);
        // 场景值处理 fr=ai 表示 股票业务的场景值 需要 拼接手机号
        if (FR_STOCK.equals(param.getFr())) {
            sceneStr = GlobalAccountSession.getUserInfo().getUserPhone() + "_" + param.getFr();
            sceneStr = sceneStr + "_" + UUID.randomUUID().toString().replace("-", "").substring(0, 8);
        } else {
            // 扫码登录或绑定场景值校验
            // 长度不能超过64
            if (sceneStr.length() > 64) {
                return ResponseResult.fail(500, "场景值长度不能超过64");
            }
            String userId = sceneStr.substring(sceneStr.lastIndexOf("_") + 1);

            if (!userId.equals("0")) {
                UserDO userDO = userMapper.selectById(Integer.valueOf(userId));
                if (userDO == null) {
                    return ResponseResult.fail(500, "用户不存在，绑定失败！");
                }
            }
        }
        if (!StringUtils.hasText(param.getSceneValue())) {
            return ResponseResult.fail(500, "场景值不能为空");
        }
        try {
            CreateQrCodeResponse response = wechatService.createQrCode(sceneStr, param.getExpireSeconds());

            if (response != null && StringUtils.hasText(response.getTicket())) {
                QrCodeResult result = new QrCodeResult();
                result.setTicket(response.getTicket());
                result.setUrl(response.getUrl());
                result.setSceneStr(sceneStr);
                result.setImageUrl(wechatService.getQrCodeImageUrl(response.getTicket()));
                result.setExpireSeconds(response.getExpireSeconds());

                return ResponseResult.success(result);
            } else {
                return ResponseResult.fail(500, "生成二维码失败");
            }
        } catch (Exception e) {
            log.error("生成微信二维码异常", e);
            return ResponseResult.fail(500, "生成二维码异常");
        }
    }

}
